<template>
  <div>
    <main-layout>
      <template v-slot:top>
        <el-form ref="searchForm" :inline="true" :model="searchInfo">
          <el-form-item label="ID">
            <el-input v-model="searchInfo.userId" placeholder="ID" clearable />
          </el-form-item>
          <el-form-item label="用户名">
            <el-input v-model="searchInfo.userName" placeholder="用户名" clearable />
          </el-form-item>
          <el-form-item label="使用人">
            <el-input v-model="searchInfo.realName" placeholder="使用人" clearable />
          </el-form-item>
          <el-form-item label="所属公司">
            <el-input v-model="searchInfo.company" placeholder="所属公司" clearable />
          </el-form-item>
          <el-form-item label="是否失效">
            <el-select v-model="searchInfo.deleteStatus" clearable placeholder="请选择是否失效" style="width: 140px;">
              <el-option value="" label="全部" />
              <el-option :value="2" label="是" />
              <el-option :value="1" label="否" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button size="small" type="primary" icon="search" @click="onSubmit">查询</el-button>
            <el-button size="small" icon="refresh" @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
      </template>

      <div class="gva-btn-list">
        <auth-tag code="ccount:insert">
          <el-button size="small" type="primary" icon="plus" @click="openAdd">新增用户</el-button>
        </auth-tag>
        
        <auth-tag code="account:delete">
          <el-button size="small" type="danger" plain icon="delete" @click="delMore">删除用户</el-button>
        </auth-tag>
      </div>

      <c-table ref="tableRef" :page="{ pageSize, pageIndex, total }" :lists="tableData" @current-change="handleCurrentChange"
        @size-change="handleSizeChange" :loading="loading" showCheck @selection-change="selectionChange" rowKey="userId" selectKey='userId'>
        <el-table-column align="center" label="ID" min-width="150" prop="userId" />
        <el-table-column align="center" label="用户名" min-width="110" prop="userName" />
        <el-table-column align="center" label="使用人" min-width="120" prop="realName" />
        <el-table-column align="center" label="角色" min-width="180" prop="roleNames" />
        <el-table-column align="center" label="所属公司" min-width="120" prop="company" />
        <el-table-column align="center" label="所属部门" min-width="120" prop="department" />
        <el-table-column align="center" label="是否失效" min-width="120" prop="">
          <template #default="scope">
            {{ scope.row.deleteStatus==1?'否':(scope.row.deleteStatus==2?'是':'')}}
          </template>
        </el-table-column>
        <el-table-column align="center" label="新增时间" width="160" >
          <template #default="scope">
            {{ formatDateLong(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="失效时间" width="160" >
          <template #default="scope">
            {{ formatDateLong(scope.row.expiryTime) }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作人" min-width="120" prop="updateUserName" />
        <el-table-column align="center" label="操作时间" width="160" >
          <template #default="scope">
            {{ formatDateLong(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" :width="oWidth" fixed="right" v-if="oWidth">
          <template #default="scope">
            <auth-tag code="account:get">
              <el-button type="text" icon="search" size="small" @click="openEdit(scope.row,3)">查看</el-button>
            </auth-tag>
            <auth-tag code="account:update">
              <el-button type="text" icon="edit" size="small" @click="openEdit(scope.row,2)">编辑</el-button>
            </auth-tag>
            <auth-tag code="account:delete">
              <el-button type="text" icon="delete" size="small" @click="del([scope.row.userId])">删除</el-button>
            </auth-tag>
          </template>
        </el-table-column>
      </c-table>

      <addUser v-if="addUserFlag" v-model:show="addUserFlag" :title="opreatType==1?'新增账户':(opreatType==2?'编辑账户':'查看账户')" @success="getTableData" :type="opreatType" :editData="editData"/> 

    </main-layout>

  </div>
</template>

<script setup>
import { nextTick, ref, watch, onActivated,reactive } from 'vue'
import {getAccountList,getAccountDetail,delAccount} from '@/api/user'
import { ElMessageBox } from 'element-plus'

import mainLayout from '@/components/custom/mainLayout.vue'
import cTable from '@/components/custom/cTable.vue'
import addUser from './components/addUser.vue'

import {formatDateLong,phoneReplace,formatDate} from '@/utils/format'

import { useUserStore } from '@/pinia/modules/user'
import {exportToExcel} from '@/utils/exportExcel'
import {message} from '@/utils/element'
import { emitter } from '@/utils/bus.js'


const userStore = useUserStore()
onActivated(() => {
  if (userStore.pageInit) { // 需要刷新页面
    init()
  } else if (userStore.refreshFn) { // 刷新函数存在，在执行
    userStore.refreshFn()
  }
})


const pageIndex = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const searchInfo = ref({})
const loading = ref(true)
const addUserFlag = ref(false)
const tableRef = ref(null)
const editData = ref({})
const opreatType = ref(1)


const init = () => {
  pageIndex.value = 1
  onReset()
  computeOpraterWidth()
  getTableData()
}

const onReset = () => {
  searchInfo.value = {}
}
// 搜索
const onSubmit = () => {
  pageIndex.value = 1
  tableRef.value.clear_selection()  // 清空所选
  getTableData()
}
// 分页
const handleSizeChange = (val) => {
  pageIndex.value = 1
  pageSize.value = val
  getTableData()
}

const handleCurrentChange = (val) => {
  pageIndex.value = val
  getTableData()
}

// 查询
const getTableData = async () => {
  //searchInfo.value.userId && (searchInfo.value.userId = parseInt(searchInfo.value.userId))
  const res = await getAccountList({ page: pageIndex.value, size: pageSize.value, ...searchInfo.value })
  if (res.code === 200) {
    tableData.value = res.data
    total.value = res.total
  }
  if(res.status==403){
    ElMessageBox.confirm('无权访问','提示',
      {
          confirmButtonText: '确定',
          showCancelButton:false,
          type: 'warning',
      }).then(async () => {
        emitter.emit('closeThisPage') // 关闭当前页面
      })
  }
  loading.value = false
}

let tableCheckeds = ref([])
const selectionChange= (items)=>{
  tableCheckeds.value = items
  //console.log("tableCheckeds",tableCheckeds.value)
}

const openAdd = ()=>{
  opreatType.value = 1
  editData.value = {}
  addUserFlag.value = true
}

const openEdit = async (item,type)=>{
  opreatType.value = type
  const res = await getAccountDetail(item.userId) // 获取详情
  if(res.code == 200){
    editData.value = res.data
    addUserFlag.value = true
  }else{
    message('获取数据失败',3)
  }
}
const del = (userIdList)=>{
  ElMessageBox.confirm(
    '确认删除该数据吗?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
      const res = await delAccount({userIdList})
      //if(res.code == 200){
        message('删除成功',2)
      getTableData()
      //}
  }).catch(() => {
      
  })
}
const delMore = ()=>{
  if(tableCheckeds.value.length<1){
   return message('请选择需要删除的数据',3)
  }
  del(tableCheckeds.value)
}

// 计算表格操作栏宽度
const oWidth = ref('60')
const computeOpraterWidth = ()=>{
  let farr = []
  const arr = ['account:get','account:update','account:delete']
  const plists = userStore.userInfo.permissionUserList // 权限数组
  for(let i=0;i<arr.length;i++){
    const sitem = arr[i]
    const fitem = plists.find(item =>(item.code && item.code.indexOf(sitem)>-1))
    if(fitem){ 
      farr.push(sitem)
      continue;  
    } 
  }
  const l_width= 70  // 2个文字按钮站占的宽度
  if(farr.indexOf('role:userList')>-1){
    oWidth.value = 90 + (farr.length-1) * l_width
  }else{
    oWidth.value = farr.length * l_width
  }
}


</script>

<style lang="scss" scoped>
.inputLine {
  display: flex;
  width: 200px;
  .zhi{
    padding: 0 10px;
  }
  s{
    font-style: normal;
    text-decoration: none;
    padding: 0 0 0 5px;
    color: var(--el-text-color-regular);
  }
}
</style>
